package com.quick.android.update;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Timer;
import java.util.TimerTask;

import com.quick.android.R;
import com.quick.android.app.App;
import com.quick.android.app.AppConfig;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

/**
 * 更新服务
 * 
 * @author quick
 * 
 */
public class UpdateService extends Service {
	static final int HANDLER_LAODING = 0;
	static final int HANDLER_LOADED = 2;
	static final int BUF_SIZE = 2048;
	private Notification notification = null;
	private NotificationManager manager = null;
	private String filePath;
	private String url;
	private long size;
	private String version;
	private Timer mTimer;
	private boolean tag = true;
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == HANDLER_LAODING) {
				sendLoadingProgress();
			} else if (msg.what == HANDLER_LOADED) {
				sendLoadedState();
				stopSelf();
			}
		};
	};

	private void sendLoadingProgress() {
		File file = new File(filePath);
		long downloadedSize = 0;
		if (file.exists()) {
			downloadedSize = file.length();
		}
		notification = new Notification(R.drawable.ic_launcher, "开始下载"
				+ getString(R.string.app_name), System.currentTimeMillis());
		if (tag) {
			notification.defaults = Notification.DEFAULT_SOUND;
			tag = false;
		}
		Intent intent = new Intent();
		PendingIntent pi = PendingIntent.getActivity(UpdateService.this, 0,
				intent, 0);
		RemoteViews rv = new RemoteViews(UpdateService.this.getPackageName(),
				R.layout.update_notification_view);
		float progress = (float) downloadedSize / (float) size;
		rv.setProgressBar(R.id.progressbar, 100, (int) (progress * 100f), false);
		rv.setTextViewText(R.id.status, ((int) (progress * 100)) + "%");
		notification.contentView = rv;
		notification.contentIntent = pi;
		manager.notify(R.drawable.ic_launcher, notification);
	}

	private boolean isDownloaded(long fileSize) {
		File file = new File(filePath);
		if (file.exists()) {
			if (file.length() == fileSize) {
				return true;
			} else if (file.length() > fileSize) {
				file.delete();
			}
		}
		return false;
	}

	private void sendLoadedState() {
		mTimer.cancel();
		boolean downloadStatus = isDownloaded(size);
		if (downloadStatus) {
			notification = new Notification(R.drawable.ic_launcher,
					getString(R.string.app_name) + "下载完成",
					System.currentTimeMillis());
		} else {
			notification = new Notification(R.drawable.ic_launcher,
					getString(R.string.app_name) + "下载失败",
					System.currentTimeMillis());
		}
		notification.defaults = Notification.DEFAULT_SOUND;
		Intent installIntent = new Intent();
		if (downloadStatus) {
			installIntent.setAction(android.content.Intent.ACTION_VIEW);
			String appType = "application/vnd.android.package-archive";
			installIntent.setDataAndType(Uri.fromFile(new File(filePath)),
					appType);
		}
		PendingIntent pi = PendingIntent.getActivity(UpdateService.this, 0,
				installIntent, 0);
		RemoteViews rv = new RemoteViews(UpdateService.this.getPackageName(),
				R.layout.update_notification_view);
		rv.setProgressBar(R.id.progressbar, 100, 100, false);
		rv.setTextViewText(R.id.status, downloadStatus ? "下载成功！" : "下载失败！");
		notification.contentView = rv;
		notification.contentIntent = pi;
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		manager.notify(R.drawable.ic_launcher, notification);
	}

	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		url = intent.getStringExtra("url");
		version = intent.getStringExtra("version");
		size = intent.getLongExtra("size", 0);
		filePath = AppConfig.getCacheFileDir(this)
				+ getString(R.string.app_name) + "v" + version + ".apk";
		manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(HANDLER_LAODING);
			}
		}, 0, 1000);
		new Thread() {
			public void run() {
				super.run();
				if (url == null) {
					mHandler.sendEmptyMessage(HANDLER_LOADED);
					return;
				}
				File file = new File(filePath);
				InputStream in = null;
				FileOutputStream out = null;
				byte[] buf = new byte[2048];
				try {
					URL u = new URL(url);
					URLConnection conn = u.openConnection();
					size = conn.getContentLength();
					if (isDownloaded(size)) {
						mHandler.sendEmptyMessage(HANDLER_LOADED);
						return;
					}
					in = conn.getInputStream();
					out = new FileOutputStream(filePath);

					int i;
					while ((i = in.read(buf)) != -1) {
						out.write(buf, 0, i);
					}
					return;
				} catch (Exception e) {
					if (file.exists()) {
						file.delete();
					}
					e.printStackTrace();
				} finally {
					if (out != null) {
						try {
							out.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					mHandler.sendEmptyMessage(HANDLER_LOADED);
				}
				return;
			};
		}.start();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	};

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}
